﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
namespace Rabbit.Utils
{
    public class JsonHelper
    {
        /// <summary>
        /// Deserizlized an json string to an object
        /// </summary>
        /// <typeparam name="T">the type to be deserialized</typeparam>
        /// <param name="json">json string</param>
        /// <returns>object of type T</returns>
        public static T Deserialize<T>(string json)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

            Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
            T obj = (T)serializer.ReadObject(stream);
            stream.Close();

            return obj;
        }

        /// <summary>
        /// serialize an object to json string
        /// </summary>
        /// <typeparam name="T">object type to be serialized</typeparam>
        /// <param name="obj">the object to be serized</param>
        /// <returns></returns>
        public static string Serialize<T>(T obj)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

            MemoryStream memStream = new MemoryStream();
            serializer.WriteObject(memStream, obj);
            string jsonString = Encoding.UTF8.GetString(memStream.GetBuffer(), 0, (int)memStream.Length);
            memStream.Close();
            return jsonString;
        }
    }
}
